package library.net.retrofit.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import library.common.util.SharedUtils;
import okhttp3.Request;

/**
 * OkHttpClient.Builder().addInterceptor
 *
 * @author Created by qiang.hou on 2017/11/19.
 * @version 1.0
 */
public class RxCommonHeaderInterceptor extends BaseParamsInterceptor {

    public RxCommonHeaderInterceptor() {
        super.control = Type.UPDATE;
    }

    public RxCommonHeaderInterceptor(Type t) {
        super.control = t;
    }

    /**
     * add header
     *
     * @param key   key
     * @param value value
     */
    public void addHeader(String key, Object value) {
        if (contentMap.containsKey(key)) {
            contentMap.remove(key);
        }
        contentMap.put(key, value);
    }

    /**
     * remove header
     *
     * @param key key for header
     */
    public void removeHeader(String key) {
        if (contentMap.containsKey(key)) {
            contentMap.remove(key);
        }
    }

    /**
     * add headers
     *
     * @param headerParamsMap headerParamsMap
     */
    public void addHeaders(Map<String, Object> headerParamsMap) {
        for (Map.Entry<String, Object> params : headerParamsMap.entrySet()) {
            addHeader(params.getKey(), params.getValue());
        }
    }

    /**
     * clear headers
     */
    public void clearHeaders() {
        contentMap.clear();
    }

    @Override
    Request interceptor(Request request) throws UnsupportedEncodingException {
        // 新的请求
        Request.Builder requestBuilder = request.newBuilder();
        requestBuilder.method(request.method(), request.body());

        // 添加公共参数,添加到header中
        if (contentMap.size() > 0) {
            for (Map.Entry<String, Object> headParams : contentMap.entrySet()) {
                switch (control) {
                    case ADD:
                        requestBuilder.addHeader(headParams.getKey(),
                                headParams.getValue() == null ? "" : getValueEncoded((String) headParams.getValue()));
                        break;
                    case UPDATE:
                        requestBuilder.header(headParams.getKey(),
                                headParams.getValue() == null ? "" : getValueEncoded((String) headParams.getValue()));
                        break;
                    case REMOVE:
                        break;
                    default:
                        break;
                }
            }
        }
        // 每个请求携带对应的缓存时间戳
        String TIME_STAMP = "If-Modified-Since";
        requestBuilder.header(TIME_STAMP, SharedUtils.getString(request.url().toString(), "-1"));
        return requestBuilder.build();
    }
}
